import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_type.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/bean/company_choose_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_address_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_branch_bean.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/bean/edit_user_info_response_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_course_class/course_class_bean/class_course_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/edit_user_page_view_model.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/widgets/edit_user_edit_widget.dart';
import 'package:e_reception_flutter/ui/mypage/toolTipBoxNewPage.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';

import '../../app_main.dart';
import 'bean/edit_user_upload_bean.dart';

/// 编辑用户
///
/// @author: zengxiangxi
/// @createTime: 3/18/21 11:38 AM
/// @specialDemand:
class EditUserPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "EditUserPage";

  final String fuid;

  final String fid;

  final String pages;

  const EditUserPage({Key key, this.fuid, this.fid, this.pages}) : super(key: key);

  @override
  EditUserPageState createState() => EditUserPageState();

  ///跳转方法
  static Future<bool> navigatorPush(BuildContext context, String fuid,String fid,{String pages}) {
    return RouterUtils.routeForFutureResult<bool>(
      context,
      EditUserPage(fuid: fuid,fid: fid,pages:pages),
      routeName: EditUserPage.ROUTER,
    );
  }
}

class EditUserPageState extends BaseState<EditUserPage> {
  EditUserPageViewModel _viewModel;

  EditUserUploadBean _mUploadBean;

  ValueNotifier<bool> _isAllowConfirmValueNotifier;

  ValueNotifier<String> _updateNameValueNotifier;

  // EditUserInfoDataBean infoDataBean0;
  PersonDetailResponseBean infoDataBean;
  FaceUserInfoBean faceUserInfo;

  List<FuserBranchListBean> fuserBranchList;

  // List<String> fuserAddressids = new List<String>();
  List<String> fuserAddBranchids = new List<String>();
  List<String> fuserRemoveBranchids = new List<String>();
  List<String> fuserAddressNameList = new List<String>();
  String fuserAddressNames = "";
  // String editButtonText;
  List<CompanyBranchListInfoBean> listBranchBean;
  // StreamSubscription streamSubscription;

  @override
  void initState() {
    super.initState();
    fuserBranchList = List<FuserBranchListBean>();
    _viewModel = EditUserPageViewModel(this);
    _updateNameValueNotifier = ValueNotifier(null);
    _isAllowConfirmValueNotifier = ValueNotifier(false);
    _mUploadBean = EditUserUploadBean(infoDataBean?.data?.faceUserInfo?.napicurl);
    //变化监听
    _mUploadBean.addListener(_notifyValue);
    _viewModel.getUserInfoBean(widget.fuid);
    // streamSubscription =
    //     VgEventBus.global.on<SuperAdminRefreshEven>()?.listen((event) {
    //       _mUploadBean.addListener(_notifyValue);
    //       _viewModel.getUserInfoHttp(widget.fuid);
    //       _viewModel.userInfoValueNotifier.addListener(_refreshInfo);
    //       setState(() { });
    //     });

    _viewModel.infoValueNotifier.addListener(_refreshInfo);
  }

  @override
  void dispose() {
    _viewModel.infoValueNotifier.removeListener(_refreshInfo);
    _isAllowConfirmValueNotifier.dispose();
    _updateNameValueNotifier?.dispose();
    _mUploadBean.removeListener(_notifyValue);
    // streamSubscription?.cancel();
    super.dispose();
  }

  void _notifyValue() {
    // print("数据更新了: ${_mUploadBean.toString()}");
    // String errorMsg = _mUploadBean.checkChangeMsg(infoDataBean);
    String errorMsg = _mUploadBean.checkAllowConfirmForErrorMsg();
    if (errorMsg == null || errorMsg.isEmpty) {
      _isAllowConfirmValueNotifier.value = true;
    } else {
      _isAllowConfirmValueNotifier.value = false;
    }
  }

  void _addressInfo(){
    listBranchBean = List<CompanyBranchListInfoBean>();
    fuserBranchList = infoDataBean?.data?.fuserBranchList;
    fuserBranchList?.forEach((element) {
      CompanyBranchListInfoBean addbean = CompanyBranchListInfoBean();
      addbean?.cbid = element?.cbid;
      addbean?.address = element?.address;
      addbean?.selected = true;
      addbean?.addrProvince = element?.addrProvince;
      addbean?.addrCity = element?.addrCity;
      addbean?.addrDistrict = element?.addrDistrict;
      addbean?.branchname = element?.getAddressStr();
      listBranchBean?.add(addbean);
      fuserAddressNameList?.add(element?.getAddressStr());
    });
    // fuserAddressNames = _addressStr(fuserAddressNameList);
    fuserAddressNames = VgStringUtils?.getMultipleStr(fuserAddressNameList);
  }

  void _refreshInfo() {
    infoDataBean = _viewModel.infoValueNotifier.value;
    faceUserInfo = infoDataBean?.data?.faceUserInfo;
    _addressInfo();
    //赋值初始化
    _mUploadBean
     ..createuid = faceUserInfo.createuid
      ..fid = widget.fid
      ..fuid = widget.fuid
      ..userid = faceUserInfo?.userid
      ..nick = faceUserInfo?.nick
      ..name = faceUserInfo?.name
      ..phone = faceUserInfo?.phone
      ..cityId = faceUserInfo?.city
      ..cityName = faceUserInfo?.city
      ..projectId = faceUserInfo?.projectid
      ..projectName = faceUserInfo?.projectname
      ..departmentId = faceUserInfo?.departmentid
      ..departmentName = faceUserInfo?.department
      ..gradeId = (faceUserInfo?.showClassInfo?.map((e) => e?.classid)?.toList()?.join(','))??''//所在班级id
      ..gradeName=(faceUserInfo?.showClassInfo?.map((e) => e?.classname)?.toList()?.join('、'))??''//所在班级名
      ..classList=faceUserInfo?.showClassInfo?.map((e) => ClassCourseListItemBean(e?.classname,e?.classid))?.toList()//所在班级
      ..userNumber = faceUserInfo?.number
      ..identityType = CompanyAddUserEditInfoIdentityExtension.getIdToTypeStr(
          faceUserInfo?.roleid)
      ..identityName = CompanyAddUserEditInfoIdentityExtension.getIdToTypeStr(
          faceUserInfo?.roleid)
          .getTypeToStr()
      ..isManagerTerminal =
      VgRoleUtils.isSuperAdmin(faceUserInfo?.roleid) || VgRoleUtils.isCommonAdmin(faceUserInfo?.roleid)
      ..headFaceUrl = VgStringUtils.getFirstNotEmptyStrByList([
        faceUserInfo?.putpicurl,
        faceUserInfo?.napicurl,
      ])
      ..terminalList = infoDataBean?.data?.manageInfo?.MHsn?.map((e) {
        return CompanyChooseTerminalListItemBean()
          ..hsn = e?.hsn
          ..sideNumber = e?.sideNumber
          ..terminalName = e?.terminalName;
      })?.toList()
      ..classIdList=infoDataBean?.data?.manageInfo?.MClass?.map((e) => e?.classid)?.toList()
      // ..managerClassName=infoDataBean.MClassInfo.map((e) => e.classname).toList().join(',')
      ..managerClassName =_mUploadBean?.splitManagerClassName(infoDataBean?.data?.manageInfo?.MClass?.map((e) => e?.classname)?.toList()?.join(','))
      ..managerDepartmentName =_mUploadBean.splitDepartment(infoDataBean?.data?.manageInfo?.MDepartment?.map((e) => e?.department)?.toList()?.join(','))
      // ..managerDepartmentName=infoDataBean.MDepartmentInfo.map((e) => e.department).toList().join(',')
      ..departmentList=infoDataBean?.data?.manageInfo?.MDepartment?.map((e) => e?.departmentid)?.toList()
      ..groupBean = (GroupListBean()
        ..groupType = faceUserInfo?.groupType
        ..groupid = faceUserInfo?.groupid
        ..groupName = faceUserInfo?.groupName)
    ..editStudentInfo = infoDataBean?.data?.showStudentInfo?.cast()
    ..studentInfo = infoDataBean?.data?.studentInfo?.cast()
    ..branchName = fuserAddressNames
      ..listBranchBean = listBranchBean
    // ..cbid = VgStringUtils?.getSplitStr(fuserAddressids, symbol: ",");
    ..addCbids = VgStringUtils?.getSplitStr(fuserAddBranchids, symbol: ",")
    ..removeCbids = VgStringUtils?.getSplitStr(fuserRemoveBranchids, symbol: ",");
    Future.delayed(Duration(milliseconds: 0), () {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
       Scaffold(
        resizeToAvoidBottomInset: false,
        resizeToAvoidBottomPadding: false,
        backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: CommonPackUpKeyboardWidget(child: _toMainColumnWidget()),
      ),
      navigationBarColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Expanded(child: _toPlaceHolderWidget()),
        if(_roleid())
        _delUser(),
        SizedBox(height: 28,),
      ],
    );
  }

  bool _roleid(){
    if(UserRepository.getInstance().userData?.comUser?.roleid == "99"){
      if(UserRepository.getInstance().userData?.comUser?.fuid==_mUploadBean?.fuid){
        return false;
      }else return true;
    }
    if(UserRepository.getInstance().userData?.comUser?.roleid == "90"){
      if(faceUserInfo?.roleid == "10"){
        return true;
      }else return false;
    }
    if(UserRepository.getInstance().userData?.comUser?.roleid == "10"){
      return false;
    }
    return false;
  }

  Widget _delUser(){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        // Navigator.push(context, new MaterialPageRoute(builder: (context){
        //   return new UnallocatedDepartmentStaffWidget();
        // }));
        bool result =
        await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "确定删除"+"${faceUserInfo?.name??"该用户"}？删除后不可恢复",
            cancelText: "取消",
            confirmText: "删除",
            confirmBgColor: ThemeRepository.getInstance()
                .getMinorRedColor_F95355());
        if (result ?? false) {
          _viewModel?.deleteUserHttp(context,
              fuid: _mUploadBean?.fuid,
              roleid: faceUserInfo?.roleid,
              userid: faceUserInfo?.userid,pages:widget?.pages);
        }
      },
      child: Container(
        // height: 20,
        padding: const EdgeInsets.symmetric(vertical: 10),
        child: Text(
          "删除用户",
          style: TextStyle(
              color: Color(0xFFF95355),
              fontSize: 14),
        ),
      ),
    );
  }

  Widget _toPlaceHolderWidget() {
    return VgPlaceHolderStatusWidget(
        loadingStatus: infoDataBean == null, child: _toEditUserEditWidget());
  }

  Widget _toEditUserEditWidget() {
    return EditUserEditWidget(
        uploadBean: _mUploadBean,
        updateNameValueNotifier: _updateNameValueNotifier);
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      title: "编辑用户",
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: ValueListenableBuilder(
        valueListenable: _isAllowConfirmValueNotifier,
        builder: (BuildContext context, bool isAllowConfirm, Widget child) {
          return GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () async {
              // if(editButtonText == null){
              //   editButtonText = "保存";
              //   // VgEventBus.global.send(EditOrSaveButtonTextEvent());
              //   setState(() { });
              //   return;
              // }
              VgToolUtils.removeAllFocus(context);
              String errorMsg = _mUploadBean.checkAllowConfirmForErrorMsg();
              if (errorMsg != null && errorMsg.isNotEmpty) {
                _isAllowConfirmValueNotifier.value = false;
                VgToastUtils.toast(context, errorMsg);
                return;
              }
              _isAllowConfirmValueNotifier.value = true;
              _viewModel.saveUserHttp(context, _mUploadBean,faceUserInfo?.groupid, logout: (){
                  UserRepository.getInstance().clearUserInfo();
                  RouterUtils.popUntil(context, AppMain.ROUTER,
                      rootNavigator: false);
              });
            },
            child: CommonFixedHeightConfirmButtonWidget(
              isAlive: isAllowConfirm,
              width: 48,
              height: 24,
              unSelectBgColor:
                  ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
              selectedBgColor:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              unSelectTextStyle: TextStyle(
                  color: VgColors.INPUT_BG_COLOR,
                  fontSize: 12,
                  fontWeight: FontWeight.w600),
              selectedTextStyle: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w600),
              text: "保存",
            ),
          );
        },
      ),
    );
  }

  void pushNameRepeatDialog() async {
    String nick = await ToolTipBoxNewPage.navigatorPushDialog(context);
    if(nick == null || nick.isEmpty){
      return;
    }
    _updateNameValueNotifier.value = nick;
    _mUploadBean.nick = nick;
    Future((){
      _viewModel.saveUserHttp(context, _mUploadBean,faceUserInfo?.groupid);
    });
    return;
  }
}


// class EditOrSaveButtonTextEvent{}
